package com.gooluke.mybatis.parser;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * XML映射文件解析器
 */
public class XmlMapperParser {
    private final Map<String, String> sqlMap = new HashMap<>();

    public XmlMapperParser(InputStream inputStream) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(inputStream);
            parseDocument(document);
        } catch (ParserConfigurationException | SAXException | IOException e) {
            throw new RuntimeException("Failed to parse XML mapper file", e);
        }
    }

    private void parseDocument(Document document) {
        Element root = document.getDocumentElement();
        NodeList selectNodes = root.getElementsByTagName("select");
        processNodes(selectNodes);
        
        NodeList insertNodes = root.getElementsByTagName("insert");
        processNodes(insertNodes);
        
        NodeList updateNodes = root.getElementsByTagName("update");
        processNodes(updateNodes);
        
        NodeList deleteNodes = root.getElementsByTagName("delete");
        processNodes(deleteNodes);
    }

    private void processNodes(NodeList nodes) {
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);
            String id = element.getAttribute("id");
            String sql = element.getTextContent().trim();
            sqlMap.put(id, sql);
        }
    }

    public String getSql(String methodName) {
        return sqlMap.get(methodName);
    }
}